/*
 * @Description: form render page
 * @Author: Rfan
 * @Date: 2021-10-09 17:47:40
 * @LastEditTime: 2022-06-22 11:25:46
 */

import { Layout, Button, Form } from 'antd';

import { useEffect, useState } from 'react';
import { LeggoForm } from '@/components/form-builder';
import { fetchDescCardForm } from '@/api/archives/archives';
import { TConfigs } from '@/components/form-builder/interface';
import { fetchDicItemListById } from '@/api/rulesettings/dictionary';

const { Content, Sider } = Layout;
const currentLevel = 2;

const Render = () => {
  const [form] = Form.useForm();
  const leggo = LeggoForm.useLeggo();
  const [schema, setSchema] = useState({});
  const [propertyList, setPropertyList] = useState([]);

  useEffect(() => {
    const params: any = {
      atType: 1,
      atCode: 100,
      level: currentLevel
    };
    fetchDescCardForm(params).then((res) => {
      console.log(res.data);
      const { cardPropertyList, descCardFormJson } = res.data;
      const schemaModel = JSON.parse(descCardFormJson);
      setSchema(schemaModel);
      setPropertyList(cardPropertyList);
      // 渲染表单
      // @ts-ignore
      leggo.resetSchemaModel(schemaModel);
      //   // 给表单赋值
      //   form.setFieldsValue({up_level_id:123,row_id:321})
    });
  }, []);

  useEffect(() => {
    if (propertyList.length > 0) {
      propertyList.forEach((item) => {
        const { field, relationRule } = item;
        if (field.dict_type_id > 0) {
          fetchDicItemListById(field.dict_type_id).then((res) => {
            const { data } = res;
            console.log('dic item ', data);
            leggo.updateSchema(field.field_name, (configs) => {
              const { inputProps } = configs;
              inputProps.options = data.map((item: any) => {
                return { label: item.name, value: `${item.name}:${item.code}:${item.value}` };
              });
            });
          });
        }
        if (relationRule) {
          leggo.updateSchema(field.field_name, (configs) => {
            const { inputProps } = configs;
            inputProps.disabled = true;
          });
        }
      });
    }
  }, [propertyList]);

  /**
   * @description: 根据字段名称查找元数据及规则
   * @param {string} fieldName 字段名
   * @return {*}
   */
  const getPropertyItem = (fieldName: string) => {
    return propertyList.find((item) => item.field?.field_name === fieldName) || {};
  };

  /**
   * @description: 根据规则拼接传入字段的值
   * @param {string} fieldName
   * @return {*}
   */
  const generateFieldVal = (fieldName: string) => {
    console.log('generateFieldVal', fieldName);
    const { relationRule } = getPropertyItem(fieldName);
    if (relationRule) {
      console.log({ relationRule });
      const { dependRelationRule, inheritRelationRule, relationType } = relationRule;
      if (relationType === 1) {
        // 使用 dependRelationRule 规则
        if (dependRelationRule.length > 0) {
          const str: string = dependRelationRule
            .map((rule: any) => {
              if (rule.type === 1) {
                const _fieldName = rule.fieldValue.field_name;
                let _val = form.getFieldValue(_fieldName);
                const ruleFieldItem = getPropertyItem(_fieldName);
                console.log({ ruleFieldItem });

                if (ruleFieldItem?.field?.dict_type_id > 0 && _val) {
                  const _arr = _val.split(':');
                  _val = _arr[1];
                }
                return _val;
              }
              return rule.strValue;
            })
            .join('');
          form.setFieldsValue({ [fieldName]: str });
        }
      } else {
        // 使用 inheritRelationRule 规则
        // 理论用不上
      }
    }
  };

  const onValuesChange = (changedValues: any) => {
    console.log({ changedValues }, Object.keys(changedValues));
    const _key = Object.keys(changedValues)[0];
    const { linkageTargetFiledList } = getPropertyItem(_key);
    if (linkageTargetFiledList?.length > 0) {
      linkageTargetFiledList.forEach((item: any) => {
        if (item.level === currentLevel) {
          generateFieldVal(item.field_name);
        }
      });
    }
  };

  const onFinish = (vals: any) => {
    const entries = Object.entries(vals).map(([k, v]: [string, any]) => {
      return {
        fieldName: k,
        fieldValue: v
      };
    });
    console.log('entries', entries);
  };

  return (
    <>
      <Layout style={{ padding: '0 24px 24px' }}>
        <Content
          className="site-layout-background"
          style={{
            padding: 24,
            margin: 0,
            minHeight: 280
          }}
        >
          <Button
            onClick={() => {
              form.submit();
            }}
          >
            submit
          </Button>
          <LeggoForm
            leggo={leggo}
            form={form}
            onValuesChange={onValuesChange}
            onFinish={onFinish}
          />
        </Content>
      </Layout>
    </>
  );
};

export default Render;
